package com.sgb.kjwl.viewmodel.self.carMakers;

import android.app.Application;
import android.content.Context;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.alibaba.fastjson.JSON;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.model.entity.transport.CargoEntity;
import com.sgb.link.utils.RoundDialogHelper;
import com.swgk.core.base.api.ICallBack;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.self.BooleanEntity;
import com.sgb.kjwl.model.entity.self.CarriageSelectEntity;
import com.sgb.kjwl.model.entity.self.GoodsSelectEntity;
import com.sgb.kjwl.model.entity.self.OwnPathEntity;
import com.sgb.kjwl.model.entity.self.TypeChooseEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.SingleItemConstant;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.view.ui.activity.self.carMaster.EditSubscribePathActivity;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.util.MToast;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Describe:    yangLei
 * Author:
 * Date:    2021/6/18
 */
public class EditSubPathModel extends AndroidViewModel {
    //第一次设置路线
    private final String TAG_FIRST = "FIRST_SET_TAG";
    public MutableLiveData<Boolean> deleteLD = new MutableLiveData<>();
    public MutableLiveData<Boolean> saveLD = new MutableLiveData<>();
    public MutableLiveData<OwnPathEntity> packagingLD = new MutableLiveData<>();
    public MutableLiveData<List<GoodsInfoTypeEntity3>> carTypeLD = new MutableLiveData<>();
    public MutableLiveData<List<GoodsSelectEntity>> goodsTypeLD = new MutableLiveData<>();
    public MutableLiveData<List<TypeChooseEntity>> selectData = new MutableLiveData<>();

    public EditSubPathModel(@NonNull @NotNull Application application) {
        super(application);
    }

    /**
     * 新增或编辑路线
     */
    public void addOrEditPath(EditSubscribePathActivity activity, OwnPathEntity pathEntity) {
        if (pathEntity == null)
            return;
        DialogHelper.showProgressDialog(activity, null, "加载中", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getLogisticsAPI().addOrEditPaths(pathEntity).enqueue(new ICallBack<BaseEntity<BooleanEntity>>() {
            @Override
            public void onSuccess(BaseEntity<BooleanEntity> data) {
                DialogHelper.dismissProgressDialog();
                if (data.getData() != null && data.getData().isFirst()) {
                    showFirstTipDialog(activity);
                } else {
                    saveLD.postValue(true);
                }
            }
        });
    }


    /**
     * 删除路线（status 传 true）
     */
    public void deletePath(EditSubscribePathActivity activity, String id) {
        HashMap map = new HashMap();
        map.put("id", id);
        map.put("status", true);
        DialogHelper.showProgressDialog(activity, null, "加载中", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getLogisticsAPI().settingPath(map).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                DialogHelper.dismissProgressDialog();
                deleteLD.postValue(true);
            }
        });
    }

    /**
     * 根据货源No获取车辆类型
     */
    public void getCarTypeList(List<TypeChooseEntity> entities) {
        if (entities != null && entities.size() > 0) {
            String[] types;
            types = new String[entities.size()];
            for (int i = 0; i < entities.size(); i++) {
                if (!TextUtils.isEmpty(entities.get(i).getNo())) {
                    types[i] = entities.get(i).getNo();
                }
            }
            NewAPIManager.getInstance().getLogisticsAPI().getCarTypesAndLen(types).enqueue(new ICallBack<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
                @Override
                public void onSuccess(BaseEntity<List<GoodsInfoTypeEntity3>> data) {
                    carTypeLD.postValue(data.getData());
                }
            });
        } else {
            NewAPIManager.getInstance().getLogisticsAPI().getCarTypesAndLen(new String[]{""}).enqueue(new ICallBack<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
                @Override
                public void onSuccess(BaseEntity<List<GoodsInfoTypeEntity3>> data) {
                    carTypeLD.postValue(data.getData());
                }
            });
        }
    }

    /**
     * 获取货源类型
     */
    public void getGoodsTypeList() {
        NewAPIManager.getInstance().getLogisticsAPI().findGoodsTypeList().enqueue(new ICallBack<BaseEntity<List<GoodsSelectEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<GoodsSelectEntity>> data) {
                goodsTypeLD.postValue(data.getData());
            }
        });
    }


    /**
     * 检查重复城市
     */
    public boolean checkRepeatCity(List<CarriageSelectEntity> list, AddressEntity city) {
        if (list == null || list.size() == 0) {
            return false;
        }
        for (int i = 0; i < list.size(); i++) {
            CarriageSelectEntity entity = list.get(i);
            //防止选择重复城市
            if (!TextUtils.isEmpty(entity.getNo()) && entity.getNo().equals(city.getNo())) {
                MToast.showToast(getApplication(), "您已经选择该城市，请选择其他城市");
                return true;
            }
        }
        return false;
    }

    /**
     * 检查重复车型
     */
    public boolean checkRepeatType(List<CarriageSelectEntity> list, GoodsInfoTypeEntity3 type) {
        if (list == null || list.size() == 0) {
            return false;
        }
        for (int i = 0; i < list.size(); i++) {
            CarriageSelectEntity entity = list.get(i);
            //防止选择重复城市
            if (!TextUtils.isEmpty(entity.getNo()) && entity.getNo().equals(type.getNo())) {
                MToast.showToast(getApplication(), "您已经选择该车型，请选择其他车型");
                return true;
            }
        }
        return false;
    }

    /**
     * 检查提交的路线信息是否完整
     *
     * @param pathEntity
     */
    public boolean checkPathInfo(EditSubscribePathActivity activity, OwnPathEntity pathEntity) {
        if (pathEntity.getCity() == null || pathEntity.getCity().size() <= 0) {
            MToast.showToast(activity, "请至少选择一个装货地");
            return false;
        }
        if (pathEntity.getDestCity() == null || pathEntity.getDestCity().size() <= 0) {
            MToast.showToast(activity, "请至少选择一个卸货地");
            return false;
        }
        return true;
    }

    /**
     * 第一次提示
     */
    private void showFirstTipDialog(EditSubscribePathActivity activity) {
        new RoundDialog.Builder(activity)
                .title("设置成功")
                .content("一旦有新发布的货源时，我们将根据您的订阅项推送货源给您，您可在找货-订阅货源中快速查看")
                .confirm("我知道了")
                .singleBtn(true)
                .cancelable(false)
                .dismissListener(dialog -> {
                    //标识已经设置过了
                    MkvUtils.get().getMMKV().encode(TAG_FIRST, false);
                    activity.finish();
                })
                .show();
    }

    /**
     * 重新组装需要提交的数据
     *
     * @param context
     * @param entity
     */
    public void packagingData(EditSubscribePathActivity context, OwnPathEntity entity) {
        OwnPathEntity pathEntity = new OwnPathEntity();
        if (!TextUtils.isEmpty(entity.getId())) {
            pathEntity.setId(entity.getId());
        }

        pathEntity.setGoodsType(entity.getGoodsType());
        pathEntity.setCarType(entity.getCarType());

        pathEntity.setCity(new ArrayList<>());
        pathEntity.setDestCity(new ArrayList<>());
        //地址信息需要挑出来重新组合
        adjustData(entity.getCity(), pathEntity.getCity());
        adjustData(entity.getDestCity(), pathEntity.getDestCity());

        if (checkPathInfo(context, pathEntity)) {
            packagingLD.postValue(pathEntity);
        }
    }


    /**
     * 挑选出需要上传的地址数据
     */
    private void adjustData(List<CarriageSelectEntity> list, List<CarriageSelectEntity> realList) {
        for (CarriageSelectEntity sub : list) {
            if (sub.getItemType() != SingleItemConstant.TYPE_TWO) {
                realList.add(sub);
            }
        }
    }

    /**
     * 转换类型数据对象
     *
     * @param typeEntities
     * @return
     */
    public List<CarriageSelectEntity> selectToCarriage(List<TypeChooseEntity> typeEntities) {
        if (typeEntities == null)
            return null;
        List<CarriageSelectEntity> cSEntities = new ArrayList<>();
        for (TypeChooseEntity typeEntity : typeEntities) {
            CarriageSelectEntity selectEntity = new CarriageSelectEntity();
            selectEntity.setName(typeEntity.getName());
            selectEntity.setNo(typeEntity.getNo());
            cSEntities.add(selectEntity);
        }
        return cSEntities;
    }

    public void checkGoodsType(String goodsModeNo) {
        NewAPIManager.getInstance().getLogisticsAPI().checkGoodsType(goodsModeNo, "").enqueue(new ICallBack<BaseEntity<String>>() {
            @Override
            public void onSuccess(BaseEntity<String> data) {
                if (data.getCode().equals("200")) {

                } else {

                }
            }

        });
    }
    public void checkGoodsType(List<CarriageSelectEntity> entity) {
        String json  = JSON.toJSONString(entity);
    /*    NewAPIManager.getInstance().getLogisticsAPI().checkPathGoodsType(json,"","").enqueue(new ICallBack<BaseEntity<List<CarriageSelectEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CarriageSelectEntity>> data) {
                if (data.getCode().equals("200")) {
                    selectData.postValue(true);
                } else {
                    selectData.postValue(false);
                }
            }

        });*/
        NewAPIManager.getInstance().getLogisticsAPI().checkPathGoodsType(json,"","").enqueue(new Callback<BaseEntity<List<TypeChooseEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<TypeChooseEntity>>> call, Response<BaseEntity<List<TypeChooseEntity>>> response) {
                if (response.body().getCode().equals("200")) {
                    selectData.postValue(response.body().getData());
                } else {
                    selectData.postValue(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<TypeChooseEntity>>> call, Throwable t) {
                selectData.postValue(new ArrayList<>());
            }
        });
    }
}
